/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package web.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author 10592
 */
public class DBUitl {
    public static final String url = "jdbc:mysql://localhost:3306/bookshop";
    public static final String DB_USER = "root";
    public static final String DB_PWT = "root";
    private static final ThreadLocal<Connection> connectionCache = new ThreadLocal<>();

    public DBUitl() {
    }
    // 使用ThreadLocal获取Connection
    public static Connection getConnection() {
        Connection con = null;
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            con = DriverManager.getConnection(url, DB_USER, DB_PWT);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
        
    }
    public static Connection getConFromDatasource() {
        Connection con = null;
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/ezb");
            con = ds.getConnection();

        } catch (NamingException ex) {
            Logger.getLogger(DBUitl.class
                    .getName()).log(Level.SEVERE, null, ex);

        } catch (SQLException ex) {
            Logger.getLogger(DBUitl.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return con;
    }

    public static void main(String[] args) {
        DBUitl.getConnection();
    }
}
